module FamilyTreeApi
  module Person
    class Summary
      attr_accessor :name, :birth, :death, :parents, :spouse
      
      def set_values(values)
        # Convert assertions into ids
        values.each{|k,v| values[k] = v.id if v.kind_of? FamilyTreeApi::Person::Assertion::Base}
        @name = values[:name] if values[:name]
        @birth = values[:birth] if values[:birth]
        @death = values[:death] if values[:death]
        if values[:parents]
          @parents = SummaryParents.new 
          @parents.set_values(values[:parents])
        end
        @spouse = values[:spouse] if values[:spouse]
      end
      
      def to_xml
        e = REXML::Element.new("summary")
        e.add_element("name").add_attribute("assertionId",@name) if @name
        if @birth || @death
          events = e.add_element("events")
          if @birth
            event = events.add_element("event")
            event.add_attribute("type","Birth")
            event.add_attribute('assertionId',@birth)
          end
          if @death
            event = events.add_element("event")
            event.add_attribute("type","Death")
            event.add_attribute('assertionId',@death)
          end
        end
        e.add_element(@parents.to_xml) if @parents
        if @spouse
          s = e.add_element("spouses")
          s.add_attribute("spouseAssertionId",@spouse)
        end
        e
      end
      
    end
    
    class SummaryParents
      attr_accessor :father, :mother
      
      def set_values(values)
        # Convert assertions into ids
        values.each{|k,v| values[k] = v.id if v.kind_of? FamilyTreeApi::Person::Assertion::Base}
        @father = values[:father] if values[:father]
        @mother = values[:mother] if values[:mother]
      end
      
      def to_xml
        e = REXML::Element.new('parents')
        e.add_attribute('fatherAssertionId', @father) if @father
        e.add_attribute('motherAssertionId', @mother) if @mother
        e
      end
    end
  end
end